import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/views/Login.vue'
import Home from '@/views/Home.vue'
import TaskManager from '@/views/TaskManager.vue'
import UserManager from '@/views/UserManager.vue'
import DefaultLayout from '@/layouts/DefaultLayout.vue'
import { useUserStore } from '@/store/user'
import { useToastStore } from '@/store/toast'

const routes = [
  { path: '/login', name: 'Login', component: Login },
  {
    path: '/',
    component: DefaultLayout,
    children: [
      { path: '', name: 'Home', component: Home },
      { path: 'tasks', name: 'TaskManager', component: TaskManager },
      { path: 'users', name: 'UserManager', component: UserManager, meta: { requiresAdmin: true } }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token')
  const userStore = useUserStore()
  const toastStore = useToastStore()

  if (to.path === '/login') {
    if (token && !userStore.user) {
      try { await userStore.fetchUser(); return next('/') } 
      catch { localStorage.removeItem('token'); return next() }
    }
    return next()
  }

  if (!token) {
    toastStore.showToast('请先登录', 'warning')
    return next('/login')
  }

  if (!userStore.user) {
    try { await userStore.fetchUser(); return next() } 
    catch { localStorage.removeItem('token'); toastStore.showToast('请先登录', 'warning'); return next('/login') }
  }

  if (to.meta.requiresAdmin && userStore.user?.role !== 'admin') {
    toastStore.showToast('权限不足，无法访问该页面', 'danger')
    return next('/')
  }

  return next()
})

export default router
